package com.lwz.startdemo.recyclerview

import android.os.Bundle
import android.widget.Button
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.dopdxd.combase.base.BaseActivity
import com.lwz.startdemo.R
import com.lwz.startdemo.databinding.ActivityRecyclerViewBinding

class RecyclerViewActivity : BaseActivity<ActivityRecyclerViewBinding>(ActivityRecyclerViewBinding::inflate) {

    private val fruitList = ArrayList<Fruit>()
    private val msgList = ArrayList<Msg>()
    private lateinit var msgAdapter:MsgAdapter
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        mBinding.btn1.setOnClickListener {
            mBinding.recyclerView.isVisible = true
            mBinding.ll.isVisible = false
            mBinding.llInput.isVisible = false

            initFruits()
            mBinding.recyclerView.layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
            val adapter = FruitAdapter(fruitList)
            mBinding.recyclerView.adapter = adapter
        }
        mBinding.btn2.setOnClickListener {
            mBinding.recyclerView.isVisible = true
            mBinding.llInput.isVisible = true
            mBinding.ll.isVisible = false

            initMsg()
            mBinding.recyclerView.layoutManager = LinearLayoutManager(this)
            if (!::msgAdapter.isInitialized){
                msgAdapter = MsgAdapter(msgList)
            }
            mBinding.recyclerView.adapter = msgAdapter

        }

        mBinding.btnSend.setOnClickListener {
            val content = mBinding.etSend.text.toString()
            if (content.isNotEmpty()){
                val msg = Msg(content,Msg.TYPE_SENT)
                msgList.add(msg)
                //使用之前保证已经初始化完成
                msgAdapter.notifyItemInserted(msgList.size-1)
                mBinding.recyclerView.scrollToPosition(msgList.size-1)
                mBinding.etSend.setText("")
            }
        }
    }

    private fun initMsg() {
        val msg1 = Msg("Hello World",Msg.TYPE_RECEIVED)
        msgList.add(msg1)
        val msg2 = Msg("Hello who is that",Msg.TYPE_SENT)
        msgList.add(msg2)
        val msg3 = Msg("This is apple",Msg.TYPE_RECEIVED)
        msgList.add(msg3)
    }

    private fun initFruits() {
        repeat(15){
            fruitList.add(Fruit(getRandomLengthString("Apple"),R.mipmap.apple))
            fruitList.add(Fruit(getRandomLengthString("Orange"),R.mipmap.orange))
            fruitList.add(Fruit(getRandomLengthString("Banana"),R.mipmap.banala))
        }
    }

    private fun getRandomLengthString(str:String):String{
        val n = (1..20).random()
        val builder = StringBuilder()
        repeat(n){
            builder.append(str)
        }
        return builder.toString()
    }


}